﻿using Furion.Authorization;
using Furion.FriendlyException;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using ZeroAdmin.Application.Entity;
using ZeroAdmin.Core;

namespace ZeroAdmin.Web.Core;

/// <summary>
/// Jwt处理
/// </summary>
public class JwtHandler : AppAuthorizeHandler
{
    /// <summary>
    /// 授权判断逻辑
    /// </summary>
    /// <param name="context"></param>
    /// <param name="httpContext"></param>
    /// <returns></returns>
    public override async Task<bool> PipelineAsync(AuthorizationHandlerContext context, DefaultHttpContext httpContext)
    {
        // 此处已经自动验证 Jwt Token的有效性了，无需手动验证
        return await CheckAuthorzieAsync();
    }

    /// <summary>
    /// 检查权限
    /// </summary>
    /// <returns></returns>
    private static async Task<bool> CheckAuthorzieAsync()
    {
        // 此处写权限控制部分
        try
        {
            long.TryParse(UserManager.UserId, out long userId);
            return await SqlSugarHelper.Queryable<User>().AnyAsync(x => x.Id.Equals(userId) && x.PhoneNumber.Equals(UserManager.PhoneNumber));
        }
        catch (Exception ex)
        {
            Oops.Bah($"授权异常：{ex.Message}");
            return false;
        }
    }
}
